// pages/collecrecomend/collecrecomend.js
var app = getApp();
var click_industryTypeId;
var lng;
var lat;
var temporary_ary = []; //某一天的行程，临时数组

var dayListTravel=[];//整个行程

Page({

  /**
   * 页面的初始数据
   */
  data: {
    user: {},
    trip_id: 0, //行程的id
    item: {},
    collec_it: false, //是否收藏
    trip_item: {}, //推荐行程的详细信息
    travelDayList: [], //推荐行程天列表数据

    travelDay: {},

    travel_ary: [],
    clickday_index: 0,
    showModal: false,
    isedit: false,
    current_index: 0, //swipe的索引

    src: '',
    markers_index: 0, //气泡的索引图

    swiper_items: [], //swiper的内容
    clicked_callout: false, //判断点击的是气泡还是标记物
    polyline:[],//地图上的连线

    show_map:true,//决定显示图片还是列表
    travel_arrange:[],//用户/推荐行程天地点列表
    selectedFlag: [false, false, false, false],//展开折叠
    currentTab: 0,
    address_value:'',//出发地点
    out_date:'',//出发时间
  },
  /**
   *切换到列表模式 
   */
  mapSwitch:function(){
    var that = this;
    var show_map = that.data.show_map;
    show_map = !show_map;

    that.setData({
      show_map: show_map,
    })
  },
  
  /**
   * 生命周期函数--监听页面加载
   */
  onLoad: function(options) {
    
    /*******获取系统当前时间**********/
    var myDate = new Date();
    var year = myDate.getFullYear();
    var mouth = myDate.getMonth()+1;
    var date = myDate.getDate();
    
    var now_date = year + '-' + mouth + '-' + date;
 
   /*******用户信息********/
    var userInfo = app.globalData.userInfo;
    var user = app.globalData.user;
    console.log('用户信息', userInfo, user);

    var that = this;
    that.setData({
      user: userInfo,
      out_date: now_date
    })

    app.getLocation(function(result) {
      lng = result.longitude;
      lat = result.latitude;
    });

    /*****************************/
    var obj = JSON.parse(options.obj);
    var travel_id = parseInt(obj.id);
    console.log('obj=', obj);
    that.setData({
      trip_id: travel_id,
      item: obj
    })

    this.getTravel_detail();
    this.getTravelDayList();

    this.getFullDetail();
   
  },
  /**
   * 用户行程完整详细信息
   */
  getFullDetail:function(){
// userTravel_fullDetail
    var that = this;
    if (that.data.item.from_name == 'collection' || that.data.item.from_name == 'userTravel'){
      app.apiPost(app.apiList.userTravel_fullDetail, {
        content: {
          id: that.data.trip_id
        }
      }, function (res) {
        // console.log(res.content.userTravelDayList,'用户行程完整详细信息');
        for (var i = 0; i < res.content.userTravelDayList.length;i++){
          var day_list = {
            day:'',
            dayId:'',
            daySiteList:[]
          };
          
          var day_item = res.content.userTravelDayList[i];

          day_list.day = day_item.day;
          day_list.dayId = day_item.id;
          var list = [];
          for (var j = 0; j < day_item.userTravelDaySiteList.length;j++){

            var obj = day_item.userTravelDaySiteList[j];
            var item = {
              siteId: obj.siteInfo.id
            }
            list.push(item);
          }
          day_list.daySiteList = list;
         
          dayListTravel.push(day_list);

        }

      })
    }
    
  },
  /**
   * 推荐行程详细信息
   */
  getTravel_detail: function() {
    var that = this;

    var api;
    
    if (that.data.item.from_name == 'collection' || that.data.item.from_name =='userTravel'){//收藏-->用户行程
      api = app.apiList.userTravel_detail;
    } else if (that.data.item.from_name == 'recommend'){ //推荐
      api = app.apiList.travel_detail;
    }

    app.apiPost(api, {
      content: {
        id: that.data.trip_id
      }
    }, function(res) {
      console.log(res, '推荐行程详细信息');
      that.setData({
        trip_item: res.content
      })
    })
  },
  /**
   * 推荐行程天列表数据
   */
  getTravelDayList: function() {
    var that = this;

    var api;

    if (that.data.item.from_name == 'collection' || that.data.item.from_name == 'userTravel') {//收藏-->用户行程
      api = app.apiList.userTravel_travelDayList;
    } else if (that.data.item.from_name == 'recommend') { //推荐
      api = app.apiList.travelDayList;
    }

    app.apiPost(api, {
      content: {
        travelId: that.data.trip_id
      }
    }, function(res) {
      console.log(res, '推荐行程天列表数据');
      that.setData({
        travelDayList: res.content
      })
      that.post_travelDaySiteMapList(that.data.clickday_index);
      that.getTravelsite_DayList(that.data.clickday_index);
    })

  },
  /*
   *点击旅行的行程
   */
  clickDay: function(e) {
    console.log(e.target.dataset.index);
    let that = this;
    that.setData({
      clickday_index: e.target.dataset.index,
      clicked_callout: false
    })
    temporary_ary = [];//切换行程的时候，置空

    that.setData({
      polyline:[],
      selectedFlag: [false, false, false, false]
    })
    
    if (that.data.show_map == true){
      that.post_travelDaySiteMapList(that.data.clickday_index);
    }else{
      that.getTravelsite_DayList(that.data.clickday_index);
    }
     
  },
  /**
   * 推荐行程天地点地图列表数据
   */
  post_travelDaySiteMapList: function(i) {

    var that = this;
    console.log(that.data.travelDayList, '表数据');

    var obj = that.data.travelDayList[i];

    var api;

    if (that.data.item.from_name == 'collection' || that.data.item.from_name == 'userTravel') {//收藏-->用户行程
      api = app.apiList.userTravel_travelDaySiteMapList;
    } else if (that.data.item.from_name == 'recommend') { //推荐
      api = app.apiList.travelDaySiteMapList;
    }

    app.apiPost(api, {
      content: {
        travelDayId: obj.id
      }
    }, function(res) {
      console.log(res, '推荐行程天地点地图列表数据');
      var travelDay = res.content;
      that.setData({
        travelDay: travelDay,
        markers_index: 0, //切换行程，重置为0
        current_index: 0,
        swiper_items: travelDay.list
      })

      //temporary_ary
      var polyline = [];
      for (var i = 0; i < travelDay.list.length; i++) {
        var item = travelDay.list[i];
        var it = {
          siteId: item.id
        }
        temporary_ary.push(it);

        var p = {
          points:[],
          color: "#67AB17", //样式
          width: 2,
          dottedLine: true
        }
        if (i < travelDay.list.length-1){
          var pi_1 = {
            longitude: travelDay.list[i].lng,
            latitude: travelDay.list[i].lat
          }
          var pi_2 = {
            longitude: travelDay.list[i + 1].lng,
            latitude: travelDay.list[i + 1].lat
          }
          p.points.push(pi_1);
          p.points.push(pi_2);
        }else{
          // var pi_1 = {
          //   longitude: travelDay.list[travelDay.list.length - 1].lng,
          //   latitude: travelDay.list[travelDay.list.length - 1].lat
          // }
          // var pi_2 = {
          //   longitude: travelDay.list[0].lng,
          //   latitude: travelDay.list[0].lat
          // }
          // p.points.push(pi_1);
          // p.points.push(pi_2);
        }
        
        polyline.push(p)

      }
      that.setData({
        polyline: polyline
      })
      // polyline
      
     
    })
  },
  /**
   * 点击收藏
   */
  click_collec: function() {
    var that = this;
    // collec_it
    if (that.data.item.page_type == 2) return;

    var collec_item = that.data.trip_item.isCollect;
    collec_item = !collec_item;

    var it = 'trip_item.isCollect';
    that.setData({
      [it]: collec_item
    })
    console.log('收藏', that.data.collec_it);
    //addCollectTravel   delCollectTravel

    this.add_del_CollectTravel(collec_item);

  },
  /**
   * 添加/取消收藏
   */
  add_del_CollectTravel: function(parem) {
    var that = this;
    var api;
    if (parem == true) {
      api = app.apiList.addCollectTravel;
    } else {
      api = app.apiList.delCollectTravel;
    }

    app.apiPost(api, {
      content: {
        travelId: that.data.trip_id
      }
    }, function(res) {
      console.log(that.data.trip_id, res, '添加 / 取消收藏');
    })
  },
  /**
   *点击标记
   */
  tap_marker: function(e) {
    console.log(e.detail);
    var that = this;
    var list = that.data.travelDay.list;
    for (var i = 0; i < that.data.travelDay.markers.length; i++) {
      var item = that.data.travelDay.markers[i];
      if (item.id == e.detail) {

        that.setData({
          markers_index: i,
          current_index: i,
          swiper_items: list,
          clicked_callout: false
        })
        if (i == that.data.travelDay.markers.length - 1) {
          that.setData({
            current_index: i - 1
          })
        }
        break;
      }
    }

  },
  /**
   *根据行业类型获取地点列表数据
   */
  get_listData: function() {
    
    console.log('根据行业类型获取地点列表数据', click_industryTypeId);
    var that = this;
    app.apiPost(app.apiList.siteListByIndustryType, {
      content: {
        pageNum: 1,
        pageSize: 5,
        industryTypeId: click_industryTypeId,
        lng: lng,
        lat: lat
      }
    }, function(res) {
      console.log(res, '获取列表数据');

      that.setData({
        swiper_items: res.content.list
      })

    });
  },
  /**
   * 点击弹起的气泡
   */
  callouttap_tap: function(e) {
    console.log(e.detail);
    var that = this;

    that.setData({
      clicked_callout: true
    })

    for (var i = 0; i < that.data.travelDay.markers.length; i++) {
      var item = that.data.travelDay.markers[i];
      if (item.id == e.detail) {

        console.log(i, '6666');
        if (that.data.isedit == true) {
          click_industryTypeId = that.data.travelDay.list[i].industryTypeId;
          /*获取同类型的备选选项（景点/饮食/住宿..） 5个*/
          that.get_listData();
        }
        break;
      }
    }
  },
  /**
   * 点击打勾：取反
   */
  click_item: function(e) {
    console.log(e.currentTarget.dataset.item, e.currentTarget.dataset.i);

    var that = this;
    var item = e.currentTarget.dataset.item;
    console.log(item.selected, '9999', item);
    // console.log('id', item.id, that.data.travelDay.list[that.data.markers_index].id);

    if (item.selected == true || item.selected == false) { //已经操作过的选项，取反
      item.selected = !item.selected;
      console.log('1111111111111');
    } else if (that.data.markers_index > -1) {
      //未操作过的选项，但是是打勾状态，操作完，变成未选中
      if (item.id == that.data.travelDay.list[that.data.markers_index].id) {
        item.selected = false;

        that.setData({
          markers_index: -1
        })

        for (var i = 0; i < temporary_ary.length; i++) {
          var object_1 = temporary_ary[i];
          if (object_1.siteId == item.id) {
            temporary_ary.splice(i, 1);

          }
        }
        console.log('22222222222222222', temporary_ary);
        return;
      } else if (item.selected == undefined){
        item.selected = true;
      }

    } else if (item.selected == undefined) {
      //未操作过的选项，但是是未打勾状态，操作完，变成选中
      item.selected = true;
      console.log('33333333');
    }

    var obj = 'swiper_items.[' + e.currentTarget.dataset.i + ']';

    that.setData({
      [obj]: item
    })

    var obj = {
      siteId: item.id
    }
    if (item.selected == true) {
      temporary_ary.push(obj);
      console.log(temporary_ary,'eeee');
      temporary_ary = that.deteleObject(temporary_ary);
     
    } else if (item.selected == false){
      for (var i = 0; i < temporary_ary.length;i++){
        var object_1 = temporary_ary[i];
        if (object_1.siteId == item.id){
          temporary_ary.splice(i, 1);
        }
      }
    }
    console.log(temporary_ary, '22');
  },
  /**
   * 删除重复项
   */
  deteleObject:function(obj){
    var uniques = [];
    var stringify = {};
    for (var i = 0; i < obj.length; i++) {
      var keys = Object.keys(obj[i]);
      keys.sort(function (a, b) {
        return (Number(a) - Number(b));
      });
      var str = '';
      for (var j = 0; j < keys.length; j++) {
        str += JSON.stringify(keys[j]);
        str += JSON.stringify(obj[i][keys[j]]);
      }
      if (!stringify.hasOwnProperty(str)) {
        uniques.push(obj[i]);
        stringify[str] = true;
      }
    }
    uniques = uniques;
    return uniques;

  },

  /*
   *显示手机号码绑定框
   */
  show_bingphone: function(e) {
    var show = !this.data.showModal;
    this.setData({
      showModal: show
    })
  },
  /*
   *隐藏手机号码绑定框
   */
  hide_modal: function(e) {
    var show = !this.data.showModal;
    this.setData({
      showModal: show
    })
  },
  /*
   * 绑定手机号
   */
  phone_bind: function(e) {
    var that = this;

    this.setData({
      isedit: true,
      clicked_callout: false
    })
    
    console.log(e, '绑定手机号');
  },
  /**
   * 用户行程天地点列表数据
   */
  getTravelsite_DayList(i){

    var that = this;
    console.log(that.data.travelDayList, '表数据');

    var obj = that.data.travelDayList[i];

    var api;

    if (that.data.item.from_name == 'collection' || that.data.item.from_name == 'userTravel') {//收藏-->用户行程
      api = app.apiList.userTravel_travelDaySiteList;
    } else if (that.data.item.from_name == 'recommend') { //推荐
      
      api = app.apiList.travel_travelDaySiteList;
    }

    app.apiPost(api, {
      content: {
        travelDayId: obj.id
      }
    }, function (res) {
      console.log(res,'用户行程天地点列表数据');
      // travel_arrange
      // var ary = res.content;
      that.setData({
        travel_arrange: res.content
      })
    })
  },
  /*
   * 分类
   */
  category: function(e) {
    var that = this;

    var obj = {
      id: that.data.trip_item.id,
      name: that.data.trip_item.name,
      dayListTravel: dayListTravel,
      clickday_index: that.data.clickday_index,
      trip_item: that.data.trip_item,
      startDate: that.data.out_date,
      startAddress: that.data.address_value
    };
    obj = JSON.stringify(obj);
    wx.navigateTo({
      url: '../categorylist/categorylist?obj=' + obj,
    })
  },
  /*
   * 解说
   */
  commentary: function(e) {
    console.log('解说');
    this.audioCtx.pause()

    this.audioCtx.seek(0)

    this.audioCtx.play()
  },
  /*
   * 虚拟游
   */
  virtual_tour: function(e) {
    console.log('虚拟游');
  },
  /*
   * 滑块视图swiper
   */
  bindchange: function(e) {
    console.log(e, '滑块视图swiper')
  },
  /**
   * 点击之后，解说
   */
  onItemClick: function(e) {
    var that = this;
    console.log('点击', e.currentTarget.dataset.index);
    var obj = this.data.swiper_items[e.currentTarget.dataset.index];
    var src = obj.narrateAudioUrl;

    console.log(that.data.clicked_callout, '====');
    //
    if (that.data.clicked_callout == true) {
      that.setData({
        src: src,
        current_index: e.currentTarget.dataset.index,
      })
    } else {
      that.setData({
        src: src,
        markers_index: e.currentTarget.dataset.index,
        current_index: e.currentTarget.dataset.index,
      })
    }

    if (e.currentTarget.dataset.index == that.data.swiper_items.length - 1) {
      that.setData({
        current_index: e.currentTarget.dataset.index - 1
      })
    }
  },
  /**
   * 保存行程
   */
  tripData_save: function() {
    var that = this;
    var obj = {
      id: that.data.trip_id,
      name: that.data.trip_item.name,
      startDate: that.data.out_date,
      price: that.data.trip_item.price,
      validitySdate: that.data.trip_item.validitySdate,
      validityEdate: that.data.trip_item.validityEdate,
      travelType: that.data.trip_item.travelType,
      startAddress: that.data.address_value,
      dayInfo: {}
    }

    var ary = [];

    var day_id = that.data.travelDayList[that.data.clickday_index].id;

    // temporary_ary = that.deteleObject(temporary_ary);//去重

    var day_item = {
      day: that.data.clickday_index + 1,
      dayId: day_id,
      daySiteList: temporary_ary
    }

    // ary.push(day_item);

    obj.dayInfo = day_item;
    console.log(day_item, 'zezeze');
    
    // dayListTravel[that.data.clickday_index] = day_item; 
    // obj.dayList = dayListTravel;
    // 新增用户行程,addUserTravel
    app.apiPost(app.apiList.updateUserTravel, {
      content: obj
    }, function(res) {
      console.log(res, '新增用户行程');
    })
  
  },
  /**
   * 展开折叠选择
   */ 
  changeToggle: function (e) {
    return;

    var index = e.currentTarget.dataset.index;
    if (this.data.selectedFlag[index]) {
      this.data.selectedFlag[index] = false;
    } else {
      this.data.selectedFlag[index] = true;
    }

    this.setData({
      selectedFlag: this.data.selectedFlag
    })
  },
  /**
   * 切换 景点概况/地址电话/交通导航
   */
  tabNav: function (e) {

    if (this.data.currentTab === e.target.dataset.current) {
      return false;
    } else {
      this.setData({
        currentTab: e.target.dataset.current,
      })
    }
  },
  /**
   * 点击下一步
   */
  next_step:function(){
    console.log('下一步');
    var that = this;
    wx.navigateTo({
      url: '../finaltravel/finaltravel?id=' + that.data.trip_id,
    })
  },
  /**
   * 生命周期函数--监听页面初次渲染完成
   */
  onReady: function() {
    this.audioCtx = wx.createAudioContext('myAudio')
  },

  /**
   * 生命周期函数--监听页面显示
   */
  onShow: function() {
    var that = this;
    /*判断是否已经绑定手机号，已绑定，点击气泡弹出底部备选项，并区分已选和未选*/
    if (app.globalData.binding_phone == true && that.data.item.from_name == 'collection') {
      this.setData({
        isedit: true,
        clicked_callout: false
      })
    }
   
  },
  /**
   * 出发地点输入完成
   */
  bindAddrssInputBlur:function(e){

    var that = this;
    that.setData({
      address_value: e.detail.value
    })
  },
  /**
   * 选择出发时间
   */
  bindDateChange:function(e){

    var that = this;
    that.setData({
      out_date: e.detail.value
    })
  },
  /**
   * 生命周期函数--监听页面隐藏
   */
  onHide: function() {
    temporary_ary = [];//切换行程的时候，置空
  },

  /**
   * 生命周期函数--监听页面卸载
   */
  onUnload: function() {

  },

  /**
   * 页面相关事件处理函数--监听用户下拉动作
   */
  onPullDownRefresh: function() {

  },

  /**
   * 页面上拉触底事件的处理函数
   */
  onReachBottom: function() {

  },

  /**
   * 用户点击右上角分享
   */
  onShareAppMessage: function() {

  }
})

/*
*展示
点击编辑，判断是否绑定手机号，未绑定，绑定一下，已绑定，不需要弹框
编辑文字改成保存

点击地图上的气泡，(附加条件已绑定)显示当前景点名称，并且底部更新数据，推荐的是同类型的景点，打勾打叉来替换

如果是改成不同类型的地点：
点击分类，选择地点，返回上一页面，
页面上将数据替换
保存，提交

*/